package com.gopay.bis.citic.fund.operation;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.fund.vo.PageData;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.MapUtil;
import com.gopay.remote.bank.ICertHelperFund;
import org.apache.log4j.Logger;

/**
 * 加解密工具
 * @CiticFundCertHelper.java
 * @author dong-wang5@hnari.com
 * @2016年7月20日 上午10:00:41  www.gopay.com.cn Inc.All rights reserved.
 */
public class CiticFundCertHelper implements ICertHelperFund {

	private static Logger logger = Logger.getLogger(CiticFundCertHelper.class);

	@Override
	public String sign(PageData pageData) throws GopayException {
		try {
			String signBefore = MapUtil.sortStringByKey(pageData, "&");
			String signed = Utils.cartFundSignature(signBefore);
			logger.info("=====Sign before:>"+signBefore+";sign after:"+signed);
//			BankLogUtils.printB2BSignSignatureLog(baseMessage, signMessage);
			return signed;
		} catch (Exception e) {
//			BankLogUtils.printB2BSignExceptionLog(baseMessage, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6028);
		}
	}

	@Override
	public boolean verify(PageData pageData) throws GopayException {
//		try {
			String signed = pageData.getString("sign");
			//排除非签名数据
			pageData.remove(BankConstants.BANK_LOGO_CITIC);
			pageData.remove("sign");
			pageData.remove("sign_type");
			String signBefore = MapUtil.sortStringByKey(pageData, "&");
			boolean result = Utils.cartFundVerify(signBefore,signed );
			logger.info("=====Result>"+result+";sign before is:"+signBefore+";signed is:"+signed);
			return result;
//			BankLogUtils.printB2BVerifyResultLog(baseMessage, true);
//		} catch (Exception e) {
//			BankLogUtils.printB2BVerifyExceptionLog(baseMessage, e);
//			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6030);
//		}
	}

	/**
	 * 通过路径读取证书文件内容.
	 * 
	 * @param path
	 * @return
	 * @throws java.io.IOException
	 */
	private String readFile(String path) throws IOException {
		FileReader fr = new FileReader(path);
		BufferedReader br = new BufferedReader(fr);
		StringBuffer sb = new StringBuffer();
		while (br.ready()) {
			sb.append(br.readLine());
		}
		if (null != fr) {
			fr.close();
		}
		if (null != br) {
			br.close();
		}
		return sb.toString();
	}

}
